package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SaveOrderStrategyContext implements ApplicationContextAware {

    // 定义一个Map存储策略接口的实现类对象
    private static final Map<String , SaveOrderStrategy> SAVE_ORDER_STRATEGY_MAP = new HashMap<>() ;

    public static SaveOrderStrategy getSaveOrderStrategy(String payway) {
        return SAVE_ORDER_STRATEGY_MAP.get(payway) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(SaveOrderStrategy.class)
                .values()
                .forEach(saveOrderStrategy -> {
                    SAVE_ORDER_STRATEGY_MAP.put(saveOrderStrategy.getPayway() , saveOrderStrategy) ;
                });
    }
}
